<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
define('NOSESSION',true);
require_once '../core/core.php';
define('NO_ERROR_RETURN',true);
define('WXAPI',true);
set_exi(function($message,$type,$action,$url){
	ob_clean();
	exit('');
});
if($_AR['close']){
	exi('站点已关闭','error');
}
if(!empty($_RQ['appid'])){
	//开放平台代收消息处理
	$appid = ltrim($_RQ['appid'], '/');
	//先将消息体解密
	$open=core_setting('open');
	require ROOT_D.'/core/library/aes/wxBizMsgCrypt.php';
	$_AR['aes']=new WXBizMsgCrypt($open['token'], $open['key'], $open['appid']);
	$post=file_get_contents('php://input');
	$message='';
	$errCode = $_AR['aes']->decryptMsg($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $post, $message);
	if($errCode){
		exi('消息体解密失败：'.$errCode,'error');
	}
	$message=xml2array($message);
	if($message['AppId']){
		//接收ticket和取消授权通知
		if($message['InfoType']=='component_verify_ticket' && $message['ComponentVerifyTicket']){
			$open['ticket']=$message['ComponentVerifyTicket'];
			core_setting('open',$open);
			
		}
		exi('success');
	}
	//全网发布测试消息
	if($appid=='wx570bc396a51b8ff8'){
		//全网发布公众号测试
		if($message['MsgType']=='event'){
			$content=$message['Event'].'from_callback';
		}elseif($message['MsgType']=='text'){
			if($message['Content']=='TESTCOMPONENT_MSG_TYPE_TEXT'){
				$content='TESTCOMPONENT_MSG_TYPE_TEXT_callback';
			}else{
				$code=str_replace('QUERY_AUTH_CODE:','',$message['Content']);
				$info=cfc('open')->get_authorization_info($code);
				if(!$info['authorizer_access_token']){
					exi('获取access_token失败！','error');
				}
				$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$info['authorizer_access_token'];
				$data=array(
					'touser'=>$message['FromUserName'],
					'msgtype'=>'text',
					'text'=>array('content'=>$code.'_from_api'),
				);
				$data=ijson_encode($data);
				$res=cfc('http')->ihttp_request($url,$data);
				exit;
			}
		}
		$return=array(
			'ToUserName'=>$message['FromUserName'],
			'FromUserName'=>$message['ToUserName'],
			'CreateTime'=>TIMESTAMP,
			'MsgType'=>'text',
			'Content'=>$content
		);
		$return=array2xml($return);
		$errCode = $_AR['aes']->encryptMsg($return, TIMESTAMP, random(16), $encryptMsg);
		if($errCode==0){
			exit($encryptMsg);
		}
		exit;
	}
	if($appid=='wxd101a85aa106f53e'){
		//全网发布小程序测试
		$code=str_replace('QUERY_AUTH_CODE:','',$message['Content']);
		$info=cfc('open')->get_authorization_info($code);
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$info['authorizer_access_token'];
		$data=array(
			'touser'=>$message['FromUserName'],
			'msgtype'=>'text',
			'text'=>array('content'=>$code.'_from_api'),
		);
		$data=ijson_encode($data);
		cfc('http')->ihttp_request($url,$data);
		exit;
	}
	//通过微信开放平台授权的公众或小程序消息处理，先从公众号数据表查找，如果找不到，则判断为小程序，从小程序数据表查找
	$_SESSION['uniacid']= pdo_getcolumn('core_account_wechat',array('appid'=>$appid),'uniacid');
	if(!$_SESSION['uniacid']){
		//小程序
		define('WXAPP',true);
		$_SESSION['uniacid']= pdo_getcolumn('core_account_wxapp',array('appid'=>$appid),'uniacid');
	}
	if(!$_SESSION['uniacid']){
		exi('error appid','error');
	}
}elseif(!empty($_RQ['wxappid'])){
	//普通微信小程序绑定消息接收处理
	$_SESSION['uniacid'] = intval($_RQ['id']);
	$wxappid =  intval($_RQ['wxappid']);
	if(!$_SESSION['uniacid']){
		exi('error1','error');
	}
	$account=pdo_get('core_accounts',array('uniacid'=>$_SESSION['uniacid']));
	$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxappid),array('id','type','appid'));
	$signkey = array($account['token'], $_GET['timestamp'], $_GET['nonce']);
	sort($signkey, SORT_STRING);
	$signString = implode('',$signkey);
	$signString = sha1($signString);
	if($signString != $_GET['signature']){
		exi('error signature');
	}
	if(strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
		exit(htmlspecialchars($_GET['echostr']));
	}
	if(strtolower($_SERVER['REQUEST_METHOD']) != 'post') {
		exit('error8');
	}
	$postStr = file_get_contents('php://input');
	$message=xml2array($postStr);
	if(!empty($_GET['encrypt_type']) && $_GET['encrypt_type'] == 'aes') {
		require ROOT_D.'/core/library/aes/wxBizMsgCrypt.php';
		$_AR['aes'] = new WXBizMsgCrypt($account['token'], $account['aeskey'], $wxapp['appid']);
		$message='';
		$errCode = $_AR['aes']->decryptMsg($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $postStr, $message);
		if($errCode){
			exi('消息体解密失败：'.$errCode,'error');
		}
		$message = xml2array($message);
	}
	if(empty($message)){
		exi('error7','error');
	}
}else{
	//普通公众号绑定消息接收处理
	$_SESSION['uniacid'] = intval($_RQ['id']);
	if(!$_SESSION['uniacid']){
		exi('error1','error');
	}
	$_AR['uc']=pdo_get('core_accounts',array('uniacid'=>$_SESSION['uniacid']));
	$token =$_AR['uc']['token'];
	$signkey = array($token, $_GET['timestamp'], $_GET['nonce']);
	sort($signkey, SORT_STRING);
	$signString = implode($signkey);
	$signString = sha1($signString);
	if($signString != $_GET['signature']){
		exi('error signature');
	}
	if(strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
		exit(htmlspecialchars($_GET['echostr']));
	}
	if(strtolower($_SERVER['REQUEST_METHOD']) != 'post') {
		exit('error8');
	}
	$postStr = file_get_contents('php://input');
	$message=xml2array($postStr);
	$_AR['wx']=pdo_get('core_account_wechat',array('oldid'=>$message['ToUserName'],'uniacid'=>$_SESSION['uniacid']),array('id','type','appid'));
	if(!empty($_GET['encrypt_type']) && $_GET['encrypt_type'] == 'aes') {
		require ROOT_D.'/core/library/aes/wxBizMsgCrypt.php';
		$_AR['aes'] = new WXBizMsgCrypt($_AR['uc']['token'], $_AR['uc']['aeskey'], $_AR['wx']['appid']);
		$message='';
		$errCode = $_AR['aes']->decryptMsg($_RQ['msg_signature'],$_RQ['timestamp'], $_RQ['nonce'], $postStr, $message);
		if($errCode){
			exi('消息体解密失败：'.$errCode,'error');
		}
		$postStr=$message;
		$message = xml2array($message);
	}
	if(empty($message)){
		exit('error7');
	}
}
if(!$_AR['wx']){
	exi('error9','error');
}
$_SESSION['wechat_id']=$_AR['wx']['id'];
$_SESSION['openid']=$message['FromUserName'];
//整理粉丝数据
$fans=pdo_get('core_fans',array('openid'=>$message['FromUserName'],'uniacid'=>$_SESSION['uniacid']));
if(!$fans){
	if($_AR['wx']['type']==2 || $_AR['wx']['type']==4){
		$fans=cfc('account',$_AR['wx']['id'])->getfans($message['FromUserName']);
		$data=array(
			'nickname'=>$fans['nickname'],
			'openid'=>$message['FromUserName'],
			'follow'=>$fans['subscribe'],
			'avatar'=>$fans['headimgurl'],
			'sex'=>$fans['sex'],
			'type'=>2,
			'pcd'=>$fans['country'].$fans['province'].$fans['city'],
			'tagid_list'=>$fans['tagid_list']?';'.implode(';'.$fans['tagid_list']).';':'',
			'uniacid'=>$_SESSION['uniacid'],
			'wxgid'=>$_AR['wx']['id'],
			'createtime'=>TIMESTAMP
		);
	}else{
		$data=array(
			'openid'=>$message['FromUserName'],
			'uniacid'=>$_SESSION['uniacid'],
			'wxgid'=>$_AR['wx']['id'],
			'createtime'=>TIMESTAMP
		);
	}
	if($_AR['uc']['mani'] && $fans['unionid']){
		$data['unionid']=$fans['unionid'];
	}
	if($fans['unionid']){
		$mid=pdo_getcolumn('core_members',array('unionid'=>$fans['unionid']),'id');
	}
	if($mid){
		$data['mid']=$mid;
	}
	pdo_insert('core_fans',$data);
}else{
	if($fans['mid']){
		$_SESSION['uid']=$fans['mid'];
	}
}
//消息处理开始！
$returns=array();
//处理自定义菜单点击事件。除触发关键词外，其他事件不另行处理
if($message['MsgType']=='event' && $message['Event']=='CLICK'){
	$message['MsgType']='text';
	$message['Content']=$message['EventKey'];
	$message['MsgId']='from_menu';
	unset($message['Event'],$message['EventKey']);
}
//录入消息日志
if($_AR['system']['wxlog']){
	$data=var_export($message,true);
	$data=$data."\n*******************************\n";
	file_put_contents(ROOT_AT.'account_logs/'.$_SESSION['uniacid'].'.log',$data,FILE_APPEND);
}
//检查是否有插件申请了上下文，如果有，则直接发送给指定插件
$context=pdo_get('core_account_context',array('uniacid'=>$_SESSION['uniacid'],'openid'=>$message['FromUserName']),array('id','plugin','back_id','expire'));
if($context && $context['expire']>TIMESTAMP && !$message['Event']){
	//所有非事件消息都发送给上下文环境
	pdo_update('core_account_context',array('expire'=>TIMESTAMP+300),array('id'=>$context['id']));//更新上下文有效期5分钟
	$plugin=pdo_get('core_plugins',array('name'=>$context['plugin']),array('name','type'));
	if($plugin){
		if($plugin['type']==4){
				require ROOT_D.'/api/open_jyapi/function.php';
				require ROOT_D.'/api/open_jyapi/to_wqz.php';
				require ROOT_D.'/api/open_jyapi/account.php';
				require ROOT_D.'/api/open_jyapi/tplWeb.php';
				$obj=WeUtility::createModuleProcessor($plugin['name']);
				if(method_exists($obj,'respond')){
					$obj->message=parse($message);
					$obj->rule=$context['back_id'];
					$obj->inContext=true;
					$respond=$obj->respond();
				}
				if($respond){
					$respond['CreateTime']=TIMESTAMP;
					respond($respond);
				}
				exi('');
		}else{
			$plugin=p_action($plugin['name']);
			if(method_exists($plugin,'respond')){
				$resp=$plugin->respond($message);
				if($resp){
					$resp['ToUserName']=$resp['ToUserName']?$resp['ToUserName']:$message['FromUserName'];
					$resp['FromUserName']=$resp['FromUserName']?$resp['FromUserName']:$message['ToUserName'];
					$resp['CreateTime']=$resp['CreateTime']?$resp['CreateTime']:TIMESTAMP;
					respond($resp);
				}
				exi('');
			}
		}
	}
}
//根据消息类型，处理消息
if($message['MsgType']=='text'){
	$sql='SELECT `back_id` FROM ' . tablename('core_back_keyword') . ' WHERE `uniacid`=:uniacid and ((`type`=1 and `keyword`=:keyword) or (`type`=2 and `keyword` like :keywordlike) or (`type`=3 and :keyword REGEXP `keyword`))';
	$params=array(':uniacid'=>$_SESSION['uniacid'],':keyword'=>$message['Content'],':keywordlike'=>'%'.$message['Content'].'%');
	$back_ids=pdo_fetchall($sql,$params);
	$returns=array();
	if($back_ids){
		foreach($back_ids as $row){
			$temp=pdo_get('core_back',array('id'=>$row['back_id'],'status'=>1));
			if($temp){
				$temp['content']=json_decode($temp['content'],true);
				$returns[]=$temp;
			}
		}
	}
	//这里查找兼容插件的回复规则
	$sql='SELECT `rid` FROM ' . tablename('rule_keyword') . ' WHERE `uniacid`=:uniacid and `status`=1 and ((`type`=1 and `content`=:keyword) or (`type`=2 and `content` like :keywordlike) or (`type`=3 and :keyword REGEXP `content`))';
	$params=array(':uniacid'=>$_SESSION['uniacid'],':keyword'=>$message['Content'],':keywordlike'=>'%'.$message['Content'].'%');
	$rules=pdo_fetchall($sql,$params);
	if($rules){
		//查找回复内容
		foreach($rules as &$rule){
			$rule=pdo_get('rule',array('id'=>$rule['rid']));
			//检查是否图文回复
			$cover=pdo_get('cover_reply',array('rid'=>$rule['id']));
			if($cover){
				$temp=array('backtype'=>2,'content'=>array(
					array('url'=>$cover['url'],'picurl'=>$cover['thumb'],'description'=>$cover['description'],'title'=>$cover['title']),
				));
				$returns[]=$temp;
			}elseif($rule['module'] && is_file(ROOT_D.'/addons/'.$rule['module'].'/processor.php')){
				//检查是否插件回复，如果是则获取插件回复内容
				require ROOT_D.'/api/open_jyapi/function.php';
				require ROOT_D.'/api/open_jyapi/to_wqz.php';
				require ROOT_D.'/api/open_jyapi/account.php';
				require ROOT_D.'/api/open_jyapi/tplWeb.php';
				$obj=WeUtility::createModuleProcessor($rule['module']);
				if(method_exists($obj,'respond')){
					$obj->rule=$rule['id'];
					$obj->priority=$rule['displayorder'];
					$obj->reply_type=$rule['reply_type'];
					$obj->message=parse($message);
					$respond=$obj->respond();
					
				}
				if($respond){
					$respond['CreateTime']=TIMESTAMP;
					respond($respond);
				}
				exi('');
			}else{
				//其他舍弃
			}
		}
	}
}else{
	//特殊消息和事件消息均由模块订阅
	if($message['Event']){
		$receive=$message['Event'];
	}else{
		$receive=$message['MsgType'];
	}
	$receives=get_receive_types('name','id');
	//先由系统订阅相关消息
	if($receive=='unsubscribe'){
		pdo_update('core_fans',array('follow'=>0,'updatetime'=>$message['CreateTime']),array('openid'=>$message['FromUserName']));
	}
	if($receive=='subscribe'){
		pdo_update('core_fans',array('follow'=>1,'updatetime'=>$message['CreateTime']),array('openid'=>$message['FromUserName']));
		if($message['EventKey']){
			//关注事件携带参数 qrscene_
			$receive='SCAN';
			$message['EventKey']=substr($message['EventKey'],8);
		}
	}
	if($receive=='card_pass_check'){
		//卡券审核通过，如果是微信会员卡，将审核通过信息存入数据库
		$setting=uni_setting('wx_card_edit');
		if($setting && $setting['card_id'] && $setting['card_id']==$message['CardId']){
			$setting['status']=1;
			uni_setting('wx_card_edit',$setting);
		}
	}
	if($receive=='card_not_pass_check'){
		//卡券审核通过，如果是微信会员卡，将审核通过信息存入数据库
		$setting=uni_setting('wx_card_edit');
		if($setting && $setting['card_id'] && $setting['card_id']==$message['CardId']){
			$setting['status']=2;
			$setting['refuse_reason']=$message['RefuseReason'];
			uni_setting('wx_card_edit',$setting);
		}
	}
	if($receive=='user_get_card'){
		//会员领卡事件，将会员卡编号保存起来
		$setting=uni_setting('wx_card_edit');
		if($setting && $setting['card_id'] && $setting['card_id']==$message['CardId']){
			$card_code=$message['UserCardCode'];
			pdo_update('core_fans',array('wxcard_code'=>$card_code),array('uniacid'=>$_SESSION['uniacid'],'openid'=>$message['FromUserName']));
			$temp=array('backtype'=>1,'content'=>array('content'=>'领取会员卡成功！！'));
			$returns[]=$temp;
		}
		
	}
	if($receive=='SCAN'){
		//扫描带参数二维码事件，仅推送给二维码所属模块
		$qr_id=intval($message['EventKey']);
		pdo_update('core_qr',array('num +='=>1),array('id'=>$qr_id));
		$qr=pdo_get('core_qr',array('id'=>$qr_id),array('plugin','data','backid','eventtype'));
		if($qr){
			$plugin=p_action($qr['plugin']);
			if(method_exists($plugin,'qr_scan')){
				$params=array('data'=>$qr['data'],'backid'=>$qr['backid'],'eventtype'=>$qr['eventtype'],'openid'=>$message['FromUserName'],'message'=>$message);
				$plugin->qr_scan($params);
			}
			$qr['data']=json_decode($qr['data'],true);
			if($qr['data']['scantype']!='follow' && $qr['eventtype']!='1'){
				exi('');
			}
		}else{
			//老插件生成的二维码
			$qrcode=pdo_get('core_qrcode',array('ticket'=>$message['Ticket']));		
			if($qrcode){
				if($qrcode['keyword']){
					
					$rid=pdo_getcolumn('rule_keyword',array('content'=>$qrcode['keyword']),'rid');
					$rule=pdo_get('rule',array('id'=>intval($rid)));
					if($rule['module'] && is_file(ROOT_D.'/addons/'.$rule['module'].'/processor.php')){
						
						require ROOT_D.'/api/open_jyapi/function.php';
						require ROOT_D.'/api/open_jyapi/to_wqz.php';
						require ROOT_D.'/api/open_jyapi/account.php';
						require ROOT_D.'/api/open_jyapi/tplWeb.php';
						$obj=WeUtility::createModuleProcessor($rule['module']);
						$obj->rule=$rule['id'];
						$obj->priority=$rule['displayorder'];
						$obj->reply_type=$rule['reply_type'];
						$obj->message=parse($message);
						$return=$obj->respond();
						$return['CreateTime']=TIMESTAMP;
						if($return){
							respond($return);
						}
					}
				}
				exi('');
			}
			exi('');
		}
	}else{
		//接着由模块订阅处理相关消息
		$plugins=pdo_getall('core_receive',array('type'=>$receives[$receive]),array('plugin'));
		if(!empty($plugins)){
			foreach($plugins as $plugin){
				if(!$plugin['plugin']){
					continue;
				}
				$plugin=p_action($plugin['plugin']);
				if(method_exists($plugin,'receive')){
					$plugin->receive($message);
				}
			}
		}
		//模块消息订阅结束，执行其他代码
	}
}
//关注回复
if($message['Event']=='subscribe'){
	$follow=uni_setting('follow_back');
	if($follow){
		if($follow['type']==1){
			//直接设置的回复内容
			if($follow['content']){
				$content=follow_back($follow['content']);
				$temp=array('backtype'=>1,'content'=>json_decode($content,true));
				$returns[]=$temp;
			}
		}else{
			if($follow['back_id']){
				$temp=pdo_get('core_back',array('id'=>$follow['back_id'],'uniacid'=>$_SESSION['uniacid']));
				if($temp){
					$temp['content']=json_decode($temp['content'],true);
					$returns[]=$temp;
				}
			}
		}
	}
}
//默认回复
if(empty($returns) && $message['MsgType']=='text'){
	//检查是否存在已启用的第三方平台，如果存在，则将消息转发给第三方平台处理
	$develops=pdo_getall('core_account_develop',array('uniacid'=>$_SESSION['uniacid'],'status'=>1),array('url','token'),'','display desc');
	if($develops){
		foreach($develops as $develop){
			$signkey = array($develop['token'], $_GET['timestamp'], $_GET['nonce']);
			sort($signkey, SORT_STRING);
			$signString = implode($signkey);
			$signString = sha1($signString);
			$url=$develop['url']."&timestamp={$_GET['timestamp']}&nonce={$_GET['nonce']}&signature={$signString}";
			$res=cfc('http')->ihttp_request($url,$postStr);
			$res=$res['content'];
			if($res && $res!='success'){
				if($_AR['aes']){
					$errCode = $_AR['aes']->encryptMsg($res, TIMESTAMP, random(16), $encryptMsg);
					if($errCode==0){
						exit($encryptMsg);
					}
					exit;
				}
				echo $res;
				exit();
			}
		}
	}
	$follow=uni_setting('default_back');
	if($follow){
		if($follow['type']==1){
			//直接设置的回复内容
			if($follow['content']){
				$content=follow_back($follow['content']);
				$temp=array('backtype'=>1,'content'=>json_decode($content,true));
				$returns[]=$temp;
			}
		}else{
			if($follow['back_id']){
				$temp=pdo_get('core_back',array('id'=>$follow['back_id'],'uniacid'=>$_SESSION['uniacid']));
				if($temp){
					$temp['content']=json_decode($temp['content'],true);
				}
				$returns[]=$temp;
			}
		}
	}
}
//文本消息回复处理
if(!empty($returns)){
	if($_AR['wx']['type']==1 || $_AR['wx']['type']==3){
		//非认证公众号处理，只处理文本消息、图文消息、音乐消息，通过被动回复接口回复消息，一次只能回复一条。
		$return=array(
			'ToUserName'=>$message['FromUserName'],
			'FromUserName'=>$message['ToUserName'],
			'CreateTime'=>TIMESTAMP
		);
		if($returns['0']['backtype']==8){
			//$plugin=pdo_getcolumn('core_back',array('id'=>$returns['0']['id']),'plugin');
				if(!$returns['0']['plugin']){
					exi('事件回复缺少模块标识！','error');
				}
				if($returns['0']['content']['op']){
					$_RQ['op']=$returns['0']['content']['op'];
				}
				$resp=cfc($returns['0']['plugin'])->$returns['0']['content']['event']($message,$returns['0']);
				if($resp){
					$resp['ToUserName']=$resp['ToUserName']?$resp['ToUserName']:$message['FromUserName'];
					$resp['FromUserName']=$resp['FromUserName']?$resp['FromUserName']:$message['ToUserName'];
					$resp['CreateTime']=$resp['CreateTime']?$resp['CreateTime']:TIMESTAMP;
					respond($resp);
				}
				exi('');
		}
		$medias=array('3','4','5','7');
		if(!in_array($returns['0']['backtype'],$medias)){
			cfc('account',$_AR['wx']['id'])->sendBackNotice($returns['0'],$return);
		}
	}else{
		//认证公众号，通过客服接口回复消息，可同时回复多条消息
		foreach($returns as $return){
			$return_types=get_back_types('id','name');
			$medias=array('3','4','5');
			if(in_array($return['backtype'],$medias) && !$return['content']['media_id']){
				if(!$return['content']['url']){
					exi('发送图片/语音/视频消息时，未设置素材地址！','error');
				}
				$types=array('3'=>'1','4'=>'2','5'=>'3');
				$return['content']['media_id']=cfc('account')->add_media($return['content']['url'],$types[$return['backtype']]);
			}
			if($return['backtype']==6){
				$return['content']['musicurl']=tomedia($return['content']['musicurl']);
				$return['content']['thumb_media_id']=cfc('account')->add_media($return['content']['picurl'],1);
			}
			if($return['backtype']==5){
				$return['content']['thumb_media_id']=cfc('account')->add_media($return['content']['picurl'],1);
			}
			if($return['backtype']!=8){
				$return_message=array(
					'touser'=>$message['FromUserName'],
					'msgtype'=>$return_types[$return['backtype']],
					$return_types[$return['backtype']]=>$return['content']
				);
				$result=cfc('account',$_AR['wx']['id'])->sendCustomNotice($return_message);
				if(is_array($result)){
					//exi($result['message'],'error');
				}
			}else{
				if(!$return['plugin'] || !$return['content']['event']){
					exi('事件回复参数错误！','error');
				}
				if($return['content']['op']){
					$_RQ['op']=$return['content']['op'];
				}
				$resp=cfc($return['plugin'])->$return['content']['event']($message,$return);
				if($resp){
					$resp['ToUserName']=$resp['ToUserName']?$resp['ToUserName']:$message['FromUserName'];
					$resp['FromUserName']=$resp['FromUserName']?$resp['FromUserName']:$message['ToUserName'];
					$resp['CreateTime']=$resp['CreateTime']?$resp['CreateTime']:TIMESTAMP;
					respond($resp);
				}
			}
		}
	}
}
exi('success');
function respond($return){
	global $_AR;
	if(!$return){
		exit;
	}	
	if(is_array($return)){
		$return=array2xml($return);
	}
	//判断aes加密
	if($_AR['aes']){
		$errCode = $_AR['aes']->encryptMsg($return, TIMESTAMP, random(16), $encryptMsg);
		if($errCode==0){
			exit($encryptMsg);
		}
		exit;
	}
	ob_clean();
	exit($return);
}
function decryptMsg($postData){ 
	if(strlen($_AR['uc']['aeskey']) != 43) {
		died('error3');
	}
	$key = base64_decode($_AR['uc']['aeskey']. '=');
	$obj = xml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
	if(!$obj){
		died('error4');
	}
	if($obj instanceof SimpleXMLElement) {
		$packet['encrypt'] = strval($obj->Encrypt);
		$packet['to'] = strval($obj->ToUserName);
	}
	checkSignature($packet['encrypt']);
	$ciphertext_dec = base64_decode($packet['encrypt']);
		$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
		$iv = substr($key, 0, 16);
		mcrypt_generic_init($module, $key, $iv);
		$decrypted = mdecrypt_generic($module, $ciphertext_dec);
		mcrypt_generic_deinit($module);
		mcrypt_module_close($module);
		$block_size = 32;
		$pad = ord(substr($decrypted, -1));
		if ($pad < 1 || $pad > 32) {
			$pad = 0;
		}
		$result = substr($decrypted, 0, (strlen($decrypted) - $pad));
		if (strlen($result) < 16) {
			return '';
		}
		$content = substr($result, 16, strlen($result));
		$len_list = unpack("N", substr($content, 0, 4));
		$xml_len = $len_list[1];
		$xml_content = substr($content, 4, $xml_len);
		$from_appid = substr($content, $xml_len + 4);
		$appid=pdo_getcolumn('core_account_wechat',array('oldid'=>$packet['to']),'appid');
		if ($from_appid != $appid){
			died('error6');
		}
	return $xml_content;
}
function checkSignature($encrypt_msg) {
		$array = array($encrypt_msg, $_AR['uc']['token'], $_GET['timestamp'], $_GET['nonce']);
		sort($array, SORT_STRING);
		$str = implode($array);
		$str = sha1($str);
	if($str != $_GET['msg_signature']){
		died('error5');
	}
}
function p_action($plugin_name){
	static $classes = array();
	if(!$classes[$plugin_name]){
		if($plugin_name=='core'){
			$dir=ROOT_D.'/core/class/plugin_core.php';
			require_once($dir);
			$class='plugin_core';
		}else{
			$dir=ROOT_PLUGIN.$plugin_name;
			if(!is_dir($dir)){
				//插件不存在方法，就用系统的
				$plugin_name='core';
				$dir=ROOT_D.'/core/class/plugin_core.php';
				require_once($dir);
				$class='plugin_core';
			}else{
				$file=$dir.'/core.php';
				if(is_file($file)){
					require_once($file);
					$class='core_'.$plugin_name;
				}else{
					$class='plugin';
				}
			}
		}
		$classes[$plugin_name]=new $class($plugin_name);
	}
	return $classes[$plugin_name];
}
function follow_back($content){
	global $fans;
	$nickname=$fans['nickname'];
	$search=array(
		'nickname'=>$nickname,
		//'num'=>$num,
	);
	$content=cfc('tools')->replace($search,$content);
	$content=array('content'=>$content);
	$content=ijson_encode($content);
	return $content;
}
function died($message){
	exi($message);
}
//启动上下文
function start_context($plugin,$back_id){
	$check=pdo_getcolumn('core_account_context',array('uniacid'=>$_SESSION['uniacid'],'openid'=>$_SESSION['openid']),'id');
	$data=array(
		'plugin'=>$plugin,
		'expire'=>TIMESTAMP+900,
	);
	if($check){
		pdo_update('core_account_context',$data,array('id'=>$check));
	}else{
		
		$data['uniacid']=$_SESSION['uniacid'];
		$data['openid']=$_SESSION['openid'];
		if($back_id){
			$data['back_id']=$back_id;
		}
		pdo_insert('core_account_context',$data);
	}
	return true;
}
//刷新上下文
function refresh_context(){
	pdo_update('core_account_context',array('expire'=>TIMESTAMP+900),array('uniacid'=>$_SESSION['uniacid'],'openid'=>$_SESSION['openid']));
	return true;
}
//结束上下文
function end_context(){
	pdo_update('core_account_context',array('expire'=>1),array('uniacid'=>$_SESSION['uniacid'],'openid'=>$_SESSION['openid']));
	return true;
}